﻿using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;

namespace RMSWebService
{
    public class PreViewHelper
    {
        /// <summary>
        /// 预览文件 说明：word 与 excel 需传入page参数
        /// </summary>
        /// <param name="uri">文件服务器物理路径</param>
        /// <param name="htmlDic">转换后html页面文件夹</param>
        /// <param name="fileName">文件名</param>
        /// <param name="p">上下文对象</param>
        /// <returns></returns>
        public static string Preview(string uri, string htmlDic, string fileName, System.Web.UI.Page p = null)
        {
            if (string.IsNullOrEmpty(uri) || string.IsNullOrEmpty(fileName))
            {
                return "缺少必要参数，无法预览！";
            }
            var fileSplit = fileName.Split('.');
            if (fileSplit.Count() <= 1)
            {
                return "文件名不正确";
            }
            string extendName = fileSplit.Last();//拓展名
            var validateResult = ValidateExtend(extendName);//验证支持的文件格式
            if (validateResult["bool"] != "1")
            {
                return validateResult["msg"];
            }

            switch (validateResult["msg"])
            {
                case "word":
                    WordPreview.Priview(p, uri, htmlDic);
                    break;
                case "excel":
                    ExcelPreview.Priview(p, uri, htmlDic);
                    break;
                case "img":
                    return "";
                case "txt":
                    return "";
                case "pdf":
                    return "";
            }
            return null;
        }

        private static Dictionary<string, string> ValidateExtend(string fileExtend)
        {
            var result = new Dictionary<string, string>();
            string extend = fileExtend.ToLower();

            string[] wordExtends = new[] { "doc", "docx" };
            string[] excelExtends = new[] { "xls", "xlsx", "xlsm" };
            string[] imageExtends = new[] { "jpg", "png", "bmp", "gif" };
            string[] txtExtends = new[] { "txt" };
            string[] pdfExtends = new[] { "pdf" };
            string all = string.Join(",", wordExtends) + "," + string.Join(",", excelExtends) + "," + string.Join(",", imageExtends) + "," + string.Join(",", txtExtends) + "," + string.Join(",", pdfExtends);
            if (!all.Split(',').Contains(extend))
            {
                result["bool"] = "-1";
                result["msg"] = "不支持的文件格式！";
                return result;
            }
            if (wordExtends.Contains(extend))
            {
                result["bool"] = "1";
                result["msg"] = "word";
                return result;
            }
            if (excelExtends.Contains(extend))
            {
                result["bool"] = "1";
                result["msg"] = "excel";
                return result;
            }
            if (imageExtends.Contains(extend))
            {
                result["bool"] = "1";
                result["msg"] = "img";
                return result;
            }
            if (txtExtends.Contains(extend))
            {
                result["bool"] = "1";
                result["msg"] = "txt";
                return result;
            }
            if (pdfExtends.Contains(extend))
            {
                result["bool"] = "1";
                result["msg"] = "pdf";
                return result;
            }

            return result;
        }

        #region 旧代码

        ///// <summary> 
        ///// word转成html 
        ///// </summary> 
        ///// <param name="wordFileName"></param> 
        //public static void WordToHtml(object wordFileName, string htmlWord)
        //{
        //    //在此处放置用户代码以初始化页面 
        //    Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
        //    Type wordType = word.GetType();
        //    Documents docs = word.Documents;
        //    //打开文件 
        //    Type docsType = docs.GetType();
        //    Document doc = (Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true });
        //    //转换格式，另存为 
        //    string a = doc.Comments.ToString();
        //    Type docType = doc.GetType();
        //    string wordSaveFileName = wordFileName.ToString();
        //    string strSaveFileName = htmlWord + "\\" + Path.GetFileNameWithoutExtension(wordSaveFileName) + ".html";
        //    object saveFileName = (object)strSaveFileName;
        //    docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatFilteredHTML });
        //    docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
        //    //退出 Word 
        //    wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);

        //}

        ///// <summary> 
        ///// Excel转成html 
        ///// </summary> 
        //public static void ExcelToHtml(string rFilePath, string rHtmlFilePath)
        //{
        //    var repExcel = new Microsoft.Office.Interop.Excel.Application();
        //    Workbook workbook = null;
        //    //xlsFile为Excel文件路径   
        //    workbook = repExcel.Application.Workbooks.Open(rFilePath,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value);
        //    //htmlFile   是要另存的html文件名   
        //    object ofmt = XlFileFormat.xlHtml;
        //    workbook.SaveAs(rHtmlFilePath,
        //     ofmt,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     XlSaveAsAccessMode.xlNoChange,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value,
        //     Missing.Value);
        //    object osave = false;
        //    workbook.Close(osave, Missing.Value, Missing.Value);
        //}

        #endregion
    }

    /// <summary>  
    /// Excel预览方法 
    /// </summary>  
    public class ExcelPreview
    {
        public static void Priview(System.Web.UI.Page p, string inFilePath, string outDirPath = "")
        {
            Microsoft.Office.Interop.Excel.Application excel = null;
            Microsoft.Office.Interop.Excel.Workbook xls = null;
            excel = new Microsoft.Office.Interop.Excel.Application();
            object missing = Type.Missing;
            object trueObject = true;
            excel.Visible = false;
            excel.DisplayAlerts = false;

            string randomName = DateTime.Now.Ticks.ToString();  //output fileName  

            xls = excel.Workbooks.Open(inFilePath, missing, trueObject, missing,
                                        missing, missing, missing, missing, missing, missing, missing, missing,
                                        missing, missing, missing);

            //Save Excel to Html  
            object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
            Workbook wsCurrent = xls;//(Workbook)wsEnumerator.Current;  
            String outputFile = outDirPath + randomName + ".html";
            wsCurrent.SaveAs(outputFile, format, missing, missing, missing,
                              missing, XlSaveAsAccessMode.xlNoChange, missing,
                              missing, missing, missing, missing);
            excel.Quit();

            //Open generated Html  
            Process process = new Process();
            process.StartInfo.UseShellExecute = true;
            process.StartInfo.FileName = outputFile;
            process.Start();
        }

    }

    /// <summary>  
    /// PDF预览方法
    /// </summary>  
    public class PDFPreview
    {
        public static void Priview(System.Web.UI.Page p, string inFilePath)
        {
            p.Response.ContentType = "Application/pdf";

            string fileName = inFilePath.Substring(inFilePath.LastIndexOf('\\') + 1);
            p.Response.AddHeader("content-disposition", "filename=" + fileName);
            p.Response.WriteFile(inFilePath);
            p.Response.End();
        }
    }


    /// <summary>  
    /// Summary description for WordPreview  
    /// </summary>  
    public class WordPreview
    {
        public static void Priview(System.Web.UI.Page p, string inFilePath, string outDirPath = @"C:\Users\Administrator\Desktop\FilePreview\RCTest\Convert\")
        {
            object missingType = Type.Missing;
            object readOnly = true;
            object isVisible = false;
            object documentFormat = 8;
            string randomName = DateTime.Now.Ticks.ToString();
            object htmlFilePath = outDirPath + randomName + ".htm";
            string directoryPath = outDirPath + randomName + ".files";

            object filePath = inFilePath;
            //Open the word document in background  
            var applicationclass = new Microsoft.Office.Interop.Word.ApplicationClass();
            applicationclass.Documents.Open(ref filePath,
                                            ref readOnly,
                                            ref missingType, ref missingType, ref missingType,
                                            ref missingType, ref missingType, ref missingType,
                                            ref missingType, ref missingType, ref isVisible,
                                            ref missingType, ref missingType, ref missingType,
                                            ref missingType, ref missingType);
            applicationclass.Visible = false;
            Document document = applicationclass.ActiveDocument;

            //Save the word document as HTML file  
            document.SaveAs(ref htmlFilePath, ref documentFormat, ref missingType,
                            ref missingType, ref missingType, ref missingType,
                            ref missingType, ref missingType, ref missingType,
                            ref missingType, ref missingType, ref missingType,
                            ref missingType, ref missingType, ref missingType,
                            ref missingType);

            //Close the word document  
            document.Close(ref missingType, ref missingType, ref missingType);

            #region Read the Html File as Byte Array and Display it on browser
            //byte[] bytes;  
            //using (FileStream fs = new FileStream(htmlFilePath.ToString(), FileMode.Open, FileAccess.Read))  
            //{  
            //    BinaryReader reader = new BinaryReader(fs);  
            //    bytes = reader.ReadBytes((int)fs.Length);  
            //    fs.Close();  
            //}  
            //p.Response.BinaryWrite(bytes);  
            //p.Response.Flush();  
            //p.Response.End();  
            #endregion
            p.Response.Redirect(inFilePath);
            p.Response.End();


            #region Delete the Html File and Diretory 删除生成的文件
            //File.Delete(htmlFilePath.ToString());  
            //foreach (string file in Directory.GetFiles(directoryPath))  
            //{  
            //    File.Delete(file);  
            //}  
            //Directory.Delete(directoryPath);  
            #endregion
        }
        //private string urlconvertor(string imagesurl1)
        //{
        //    string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
        //    string imagesurl2 = imagesurl1.Replace(tmpRootDir, ""); //转换成相对路径
        //    imagesurl2 = imagesurl2.Replace(@"/", @"/");
        //    //imagesurl2 = imagesurl2.Replace(@"Aspx_Uc/", @"");
        //    return imagesurl2;
        //}
        ////相对路径转换成服务器本地物理路径
        //private string urlconvertorlocal(string imagesurl1)
        //{
        //    string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
        //    string imagesurl2 = tmpRootDir + imagesurl1.Replace(@"/", @"/"); //转换成绝对路径
        //    return imagesurl2;
        //}
    }

    /// <summary>  
    /// Summary description for TextFilePreview  
    /// </summary>  
    public class TextFilePreview
    {
        public static void Preview(System.Web.UI.Page p, string inFilePath)
        {
            string fileName = inFilePath.Substring(inFilePath.LastIndexOf('\\') + 1);

            p.Response.ContentType = "text/plain";
            p.Response.ContentEncoding = System.Text.Encoding.UTF8;  //保持和文件的编码格式一致  
            p.Response.AddHeader("content-disposition", "filename=" + fileName);
            p.Response.WriteFile(inFilePath);
            p.Response.End();


        }
    }

    /// <summary>  
    /// Summary description for TextFilePreview  
    /// </summary>  
    public class ImageFilePreview
    {
        public static void Preview(System.Web.UI.Page p, string inFilePath)
        {
            string fileName = inFilePath.Substring(inFilePath.LastIndexOf('\\') + 1);

            p.Response.ContentType = "images/*";
            p.Response.ContentEncoding = System.Text.Encoding.UTF8;
            p.Response.AddHeader("content-disposition", "filename=" + fileName);
            p.Response.WriteFile(inFilePath);
            p.Response.End();
        }
    }
}